//
//  ZoneAlertSettingView.m
//  EZ Tracker
//
//  Created by FENGYL on 2017/3/31.
//  Copyright © 2017年 FENGYL. All rights reserved.
//

#import "ZoneAlertSettingView.h"
#import "UserModel.h"
#import "ZoneAlertSettingCollectionViewCell.h"
#import "UIView+XL.h"
#import "NewZoneViewController.h"
#import "NetworkCommand.h"
#import "ZoneAlertsViewController.h"

#import <CoreLocation/CoreLocation.h>
#import <QuartzCore/QuartzCore.h>
#import <SVProgressHUD.h>

/* 弧度转角度 */
#define SK_RADIANS_TO_DEGREES(radian) \ ((radian) * (180.0 / M_PI))
/* 角度转弧度 */
#define SK_DEGREES_TO_RADIANS(angle) \ ((angle) / 180.0 * M_PI)

#define RADIUS_OF_EARTH_METERS 6371009;

@interface ZoneAlertSettingView()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (strong, nonatomic) UserModel *userModel;
@property (strong, nonatomic) UICollectionView *deviceCollectionView;
@property (strong, nonatomic) NSDictionary *fenceDictionary;

@property (strong, nonatomic) NSNumber *zoneType;

@property (weak, nonatomic) IBOutlet UITextField *zoneNameTextField;
@property (weak, nonatomic) IBOutlet UIButton *saveButton;
@property (weak, nonatomic) IBOutlet UIButton *safeZoneButton;
@property (weak, nonatomic) IBOutlet UIButton *dangerZoneButton;
@property (weak, nonatomic) IBOutlet UIButton *oneTimeButton;
@property (weak, nonatomic) IBOutlet UIView *deviceView;
@property (weak, nonatomic) IBOutlet UIButton *onEnterButton;
@property (weak, nonatomic) IBOutlet UIButton *onLeaveButton;
@property (weak, nonatomic) IBOutlet UISlider *radiusSlider;


@end

@implementation ZoneAlertSettingView

-(UserModel *)userModel{
    
    if (!_userModel) {
        _userModel = [[UserModel alloc]init];
    }
    return _userModel;
}

-(NSMutableArray *)selectedDeviceArray{
    
    if (!_selectedDeviceArray) {
        _selectedDeviceArray = [NSMutableArray array];
    }
    return _selectedDeviceArray;
}

-(void)setUpViewForFenceDictionary:(NSDictionary *)fenceDictionary{
    
    self.fenceDictionary = fenceDictionary;
    
    //textfield框颜色
    self.zoneNameTextField.layer.borderColor = [UIColor orangeColor].CGColor;
    self.zoneNameTextField.layer.borderWidth = 1;
    
    
    //初始化collectionView
    UICollectionViewFlowLayout *collectionViewFlowLayout = [[UICollectionViewFlowLayout alloc]init];
    //设置collectionView滚动方向
    [collectionViewFlowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    //设置headerView的尺寸大小
//    collectionViewFlowLayout.headerReferenceSize = CGSizeMake(kScreenWidth, 100);
    //该方法也可以设置itemSize
    collectionViewFlowLayout.itemSize =CGSizeMake(60, 70);

    
    self.deviceCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.deviceView.width, self.deviceView.height)collectionViewLayout:collectionViewFlowLayout];
    [self.deviceCollectionView registerClass:[ZoneAlertSettingCollectionViewCell class] forCellWithReuseIdentifier:@"ZoneAlertSettingCollectionViewCell"];
    
    [self.deviceCollectionView setBackgroundColor:[UIColor whiteColor]];
    [self.deviceView addSubview:self.deviceCollectionView];
    self.deviceCollectionView.delegate = self;
    self.deviceCollectionView.dataSource = self;
    
    
    //saveButton
    [self setViewShadow:self.saveButton];
    
    
    //radiusSlider
    [self.radiusSlider addTarget:self action:@selector(radiusSliderValueDidChanged) forControlEvents:UIControlEventValueChanged];
    
    //zoneType
    self.zoneType = @1;
    
    //有数据设置
    if (fenceDictionary) {
        
        NSString *pointsString = [fenceDictionary valueForKey:NC_POINTS];
        
        //zoneName
        [self.zoneNameTextField setText:[fenceDictionary valueForKey:NC_FENCE_NAME]];
        
        //RadiusSlider
        CGFloat radius = [[self getRadiusForPointsString:pointsString]floatValue];
        
        self.radiusSlider.value = radius/5000.0;
        
        //ZoneType
        self.zoneType = [fenceDictionary valueForKey:NC_ZONE_TYPE];
        int zoneType = [[fenceDictionary valueForKey:NC_ZONE_TYPE] intValue];
        
        if (zoneType == 0) {
            zoneType = 2;
        }
        
        self.dangerZoneButton.selected = NO;
        self.safeZoneButton.selected = NO;
        self.oneTimeButton.selected = NO;
        
        
        if (zoneType == 1) {
            
            self.safeZoneButton.selected = YES;
            
        }else if (zoneType == 2){
            
            self.dangerZoneButton.selected = YES;
            
        }else if (zoneType == 3){
            
            self.oneTimeButton.selected = YES;
            
        }
        
        
        //onEnter
        self.onEnterButton.selected = [[fenceDictionary valueForKey:NC_IS_ENTER] intValue];
        
        //onLeave
        self.onLeaveButton.selected = [[fenceDictionary valueForKey:NC_IS_LEAVE] intValue];
        
        //collectionCell
        [self.selectedDeviceArray addObject:self.userModel.selectedDeviceSerialNumber];
        [self.deviceCollectionView reloadData];
        
    }
    
}

-(CGFloat)getSaveButtonMaxY{
    
    return CGRectGetMaxY(self.saveButton.frame);
    
}

#pragma mark SafeZoneButton
- (IBAction)touchSafeZoneButton:(id)sender {
    
    self.safeZoneButton.selected = YES;
    //
    self.dangerZoneButton.selected = NO;
    self.oneTimeButton.selected = NO;
    
    
    self.zoneType = @1;
    //变颜色
    NewZoneViewController *newZoneViewController = [self getSuperController];
    
    if (newZoneViewController) {
        
        [newZoneViewController setUpMapcolor:MapCircleColorGreen];
        
    }
    
}

#pragma mark DangerZoneButton
- (IBAction)touchDangerZoneButton:(id)sender {
    
    self.dangerZoneButton.selected = YES;
    //
    self.safeZoneButton.selected = NO;
    self.oneTimeButton.selected = NO;
    
    self.zoneType = @2;
    //变颜色
    NewZoneViewController *newZoneViewController = [self getSuperController];
    
    if (newZoneViewController) {
        
        [newZoneViewController setUpMapcolor:MapCircleColorRed];
        
    }
}

#pragma mark OneTimeButton
- (IBAction)touchOneTimeButton:(id)sender {
    
    self.oneTimeButton.selected = YES;
    //
    self.safeZoneButton.selected = NO;
    self.dangerZoneButton.selected = NO;
    
    self.zoneType = @3;
    //变颜色
    NewZoneViewController *newZoneViewController = [self getSuperController];
    
    if (newZoneViewController) {
        
        [newZoneViewController setUpMapcolor:MapCircleColorBlue];
        
    }
    
}

#pragma mark OnEnterButton
- (IBAction)touchOnEnterButton:(id)sender {
    
    self.onEnterButton.selected = !self.onEnterButton.selected;
    
}

#pragma mark OnLeaveButton
- (IBAction)OnLeaveButton:(id)sender {
    
    self.onLeaveButton.selected = !self.onLeaveButton.selected;
    
}

#pragma mark 按钮阴影效果
-(void)setViewShadow:(UIView *)sender{
    
    sender.layer.shadowColor = [UIColor blackColor].CGColor;
    
    sender.layer.shadowOffset = CGSizeMake(2, 2);
    
    sender.layer.shadowOpacity = 0.4;
    
    sender.layer.shadowRadius = 4;
    
}

#pragma mark CollectionView

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.userModel.deviceByAccountArray.count;
    
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *dict = self.userModel.deviceByAccountArray[indexPath.row];
    
    ZoneAlertSettingCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ZoneAlertSettingCollectionViewCell" forIndexPath:indexPath];

    
    
    NSLog(@"selectedDeviceArray %@",self.selectedDeviceArray);
    
    //设置deviceName
    
    NSString *deviceName;
    
    if ([self.userModel.changeDeviceNameDictionary valueForKey:[dict valueForKey:NC_SERIAL_NUMBER]]) {
        
        deviceName = [self.userModel.changeDeviceNameDictionary valueForKey:[dict valueForKey:NC_SERIAL_NUMBER]];
        
    }else{
        
        deviceName = [dict valueForKey:NC_DISPLAY_NAME];
        
    }

    [cell setUpCellForSerialNumber:[dict valueForKey:NC_SERIAL_NUMBER] deviceName:deviceName isSelected:[self.selectedDeviceArray containsObject:[dict valueForKey:NC_SERIAL_NUMBER]]];
    
    
    UIImage *image = [self.userModel.deviceIconDictionary valueForKey:[dict valueForKey:NC_SERIAL_NUMBER]];
    
    [cell setUpIconImage:image];
    
    
    return cell;
}

#pragma mark raidusSlider值改变
-(void)radiusSliderValueDidChanged{
    

            
    NewZoneViewController *newZoneViewController = [self getSuperController];
    
    if (newZoneViewController) {
        
        
        
        CGFloat radius = self.radiusSlider.value * 5000;
        
        NSLog(@"radius %f radisuSliderValue %f",radius,self.radiusSlider.value);
        
        [newZoneViewController setUpMapRadius:radius];
        
    }
            
    

    
    
    
}


#pragma mark 获取父控制器
-(NewZoneViewController *)getSuperController{
    
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[NewZoneViewController class]]) {
            
            
            return (NewZoneViewController *)nextResponder;
            
        }
    }
    
    return nil;
    
}

#pragma mark 获取中心点
-(CLLocation *)getCenterPointsForPointsString:(NSString *)pointsString{
    
    if (pointsString.length > 0) {
        
        NSArray *pointArray = [pointsString componentsSeparatedByString:@"_"];
        
        NSArray *centerPointArray = [[pointArray firstObject] componentsSeparatedByString:@","];
        
        double centerLatitude = [[centerPointArray firstObject] doubleValue];
        
        double centerLongitude = [[centerPointArray lastObject] doubleValue];
        
        NSLog(@"points %f,%f",centerLatitude,centerLongitude);
        
        CLLocation *centerLocation = [[CLLocation alloc]initWithLatitude:centerLatitude longitude:centerLongitude];
        
        return centerLocation;
        
    }
    
    return nil;
}

#pragma mark 获取半径
-(NSNumber *)getRadiusForPointsString:(NSString *)pointsString{
    
    if (pointsString.length > 0) {
        
        NSArray *pointArray = [pointsString componentsSeparatedByString:@"_"];
        
        NSArray *centerPointArray = [[pointArray firstObject] componentsSeparatedByString:@","];
        
        NSArray *linePointArray = [[pointArray lastObject] componentsSeparatedByString:@","];
        
        double centerLatitude = [[centerPointArray firstObject] doubleValue];
        
        double centerLongitude = [[centerPointArray lastObject] doubleValue];
        
        double lineLatitude = [[linePointArray firstObject] doubleValue];
        
        double lineLongitude = [[linePointArray lastObject] doubleValue];
        
        NSLog(@"points %f,%f_%f,%f",centerLatitude,centerLongitude,lineLatitude,lineLongitude);
        
        CLLocation *centerLocation = [[CLLocation alloc]initWithLatitude:centerLatitude longitude:centerLongitude];
        
        CLLocation *lineLocation = [[CLLocation alloc]initWithLatitude:lineLatitude longitude:lineLongitude];
        
        int radius = [centerLocation distanceFromLocation:lineLocation];
        
        NSLog(@"radius %d",radius);
        
        return @(radius);
        
    }
    
    return nil;
}

#pragma mark
- (IBAction)touchSaveButton:(id)sender {
    
    
    if (!(_zoneNameTextField.text.length > 0)) {
        
        [SVProgressHUD showErrorWithStatus:@"Zone Name can not be empty"];
        
        [SVProgressHUD dismissWithDelay:1];
        
        return;
        
    }
    
    if (!(_selectedDeviceArray.count > 0)) {
        
        [SVProgressHUD showErrorWithStatus:@"Users can not be empty"];
        
        [SVProgressHUD dismissWithDelay:1];
        
        return;
        
    }
    
    [SVProgressHUD showWithStatus:@"Loading..."];
    
    if (!_fenceDictionary) {
        
        //points
        double centerLatitude = self.mapRegion.center.latitude;
        double centerLongitude = self.mapRegion.center.longitude;
        
        double lineLongitude = [self getLineLongitude];
        
        NSString *pointsString = [NSString stringWithFormat:@"%.5f,%.5f_%.5f,%.5f",centerLatitude,centerLongitude,centerLatitude,lineLongitude];
        
        NSLog(@"points %@",pointsString);
        
        //zoneName
        NSString *fenceName = _zoneNameTextField.text;
        
        //fenceId
        NSNumber *fenceId = @0;
        
        
        
        [NetworkCommand PutGeoFenceForPoints:pointsString fenceName:fenceName fenceId:fenceId Success:^(id responseObject) {
            
            NSDictionary *responseObjectDictionary = responseObject;
            
            //判读是否成功
            int status = [[responseObjectDictionary valueForKey:NC_STATUS] intValue];
            
            if (status != 1 ) {
                
                [SVProgressHUD showErrorWithStatus:@"Failed"];
                
                [SVProgressHUD dismissWithDelay:1];
                
                return;
                
            }
            
            //id
            NSNumber *newFenceId = [responseObjectDictionary valueForKey:NC_USER_ID];
            
            //enter leave
            NSNumber *isEnter;
            NSNumber *isLeave;
            
            if (self.onEnterButton) {
                isEnter = @1;
            }else{
                isEnter = @0;
            }
            
            if (self.onLeaveButton) {
                isLeave = @1;
            }else{
                isLeave = @0;
            }
            
            //循环添加围栏
            for (int i = 0; i < _selectedDeviceArray.count; i++) {
                
                NSString *serialNumber = _selectedDeviceArray[i];
                
                [NetworkCommand BindForBindFenceId:newFenceId ZoneType:self.zoneType isEnter:isEnter isLeave:isLeave displayName:fenceName serialNumber:serialNumber Success:^(id responseObject) {
                    
                    NSDictionary *newResponseObjectDictionary = responseObject;
                    
//                    int setStatus = [[newResponseObjectDictionary valueForKey:NC_SET_STATUS] intValue];
                    
                    int code = [[newResponseObjectDictionary valueForKey:NC_CODE] intValue];
                    
                    if (!(code >= 1) ) {
                        
                        [SVProgressHUD showErrorWithStatus:@"Failed"];
                        
                        [SVProgressHUD dismissWithDelay:1];
                        
                    }else{
                        
                        if (i >= _selectedDeviceArray.count - 1) {
                            
                            [SVProgressHUD dismissWithDelay:1];
                            
                            NewZoneViewController *newZoneViewController = [self getSuperController];
                            
                            [newZoneViewController.navigationController popViewControllerAnimated:YES];
                            
                            ZoneAlertsViewController *zoneAlertsViewController;
                            
                            
                            for (UIViewController *viewController in newZoneViewController.navigationController.viewControllers) {
                                
                                if ([viewController isKindOfClass:[ZoneAlertsViewController class]]) {
                                    
                                    zoneAlertsViewController = (ZoneAlertsViewController *)viewController;
                                    
                                    break;
                                    
                                }
                                
                            }
                            
                            
                            
                            [zoneAlertsViewController reloadFenceTableView];
                            
                            
                            
                        }
                        
                    }
                    
                } failure:^{
                    
                    [SVProgressHUD showErrorWithStatus:@"Failed"];
                    
                    [SVProgressHUD dismissWithDelay:1];
                    
                }];
                
            }
            
            
            
        } failure:^{
            
            [SVProgressHUD showErrorWithStatus:@"Failed"];
            
            [SVProgressHUD dismissWithDelay:1];
            
            
        }];
        
    }else{
        //有参数围栏
        
        NSString *pointsString = [_fenceDictionary valueForKey:NC_POINTS];
        NSString *fenceName = _zoneNameTextField.text;
        NSNumber *fenceId = [_fenceDictionary valueForKey:NC_BIND_FENCE_ID];
        
        [NetworkCommand DelGeoFenceForPoints:pointsString fenceName:fenceName fenceId:fenceId Success:^(id responseObject) {
            
            NSDictionary * delResponseObjectDictionary = responseObject;
            
            //判断是否成功
            int status = [[delResponseObjectDictionary valueForKey:NC_STATUS] intValue];
            
            if (status != 1 ) {
                
                [SVProgressHUD showErrorWithStatus:@"Failed"];
                
                [SVProgressHUD dismissWithDelay:1];
                
                return;
                
                
                
            }
            
            [NetworkCommand PutGeoFenceForPoints:pointsString fenceName:fenceName fenceId:@0 Success:^(id responseObject) {
                
                NSDictionary *responseObjectDictionary = responseObject;
                
                //判读是否成功
                int status = [[responseObjectDictionary valueForKey:NC_STATUS] intValue];
                
                if (status != 1 ) {
                    
                    [SVProgressHUD showErrorWithStatus:@"Failed"];
                    
                    [SVProgressHUD dismissWithDelay:1];
                    
                    return;
                    
                }
                
                //id
                NSNumber *newFenceId = [responseObjectDictionary valueForKey:NC_USER_ID];
                
                //enter leave
                NSNumber *isEnter;
                NSNumber *isLeave;
                
                if (self.onEnterButton) {
                    isEnter = @1;
                }else{
                    isEnter = @0;
                }
                
                if (self.onLeaveButton) {
                    isLeave = @1;
                }else{
                    isLeave = @0;
                }
                
                //循环添加围栏
                for (int i = 0; i < _selectedDeviceArray.count; i++) {
                    
                    NSString *serialNumber = _selectedDeviceArray[i];
                    
                    [NetworkCommand BindForBindFenceId:newFenceId ZoneType:self.zoneType isEnter:isEnter isLeave:isLeave displayName:fenceName serialNumber:serialNumber Success:^(id responseObject) {
                        
                        NSDictionary *newResponseObjectDictionary = responseObject;
                        
                        //                    int setStatus = [[newResponseObjectDictionary valueForKey:NC_SET_STATUS] intValue];
                        
                        int code = [[newResponseObjectDictionary valueForKey:NC_CODE] intValue];
                        
                        if (!(code >= 1) ) {
                            
                            [SVProgressHUD showErrorWithStatus:@"Failed"];
                            
                            [SVProgressHUD dismissWithDelay:1];
                            
                        }else{
                            
                            if (i >= _selectedDeviceArray.count - 1) {
                                
                                [SVProgressHUD dismissWithDelay:1];
                                
                                NewZoneViewController *newZoneViewController = [self getSuperController];
                                
                                [newZoneViewController.navigationController popViewControllerAnimated:YES];
                                
                                ZoneAlertsViewController *zoneAlertsViewController;
                                
                                
                                for (UIViewController *viewController in newZoneViewController.navigationController.viewControllers) {
                                    
                                    if ([viewController isKindOfClass:[ZoneAlertsViewController class]]) {
                                        
                                        zoneAlertsViewController = (ZoneAlertsViewController *)viewController;
                                        
                                        break;
                                        
                                    }
                                    
                                }
                                
                                
                                
                                [zoneAlertsViewController reloadFenceTableView];
                                
                                
                                
                            }
                            
                        }
                        
                    } failure:^{
                        
                        [SVProgressHUD showErrorWithStatus:@"Failed"];
                        
                        [SVProgressHUD dismissWithDelay:1];
                        
                    }];
                    
                }
                
                
                
            } failure:^{
                
                [SVProgressHUD showErrorWithStatus:@"Failed"];
                
                [SVProgressHUD dismissWithDelay:1];
                
                
            }];
            
        } failure:^{
            
            [SVProgressHUD showErrorWithStatus:@"Failed"];
            
            [SVProgressHUD dismissWithDelay:1];
            
        }];
        
        
        
        
        

        
    }
    
}

#pragma mark 计算边界纬度
-(double)getLineLongitude{
    
    double radius = 5000 * self.radiusSlider.value;
    
    double latitude = self.mapRegion.center.latitude;
    
    double radian = radius / RADIUS_OF_EARTH_METERS;
    
    double toDegress = radian * (180.0 / M_PI);
    
    double toRadians = latitude / 180.0 * M_PI;
    
    double cosToRadians = cos(toRadians);
    
    double radiusAngle = toDegress / cosToRadians;
    
    return self.mapRegion.center.longitude + radiusAngle;
    
//    double radiusAngle =
//    Math.toDegrees(radius / RADIUS_OF_EARTH_METERS) / Math.cos(Math.toRadians(center.latitude));
//    return new LatLng(center.latitude, center.longitude + radiusAngle);
    
    
    
}

@end
